package com.itic.mall.system.weixinbatch.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.common.service.OutCommonService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.system.product.persistence.model.Product;
import com.itic.mall.system.product.persistence.model.ProductExample;
import com.itic.mall.system.product.service.ProductService;
import com.itic.mall.system.weixinbatch.persistence.model.WeixinBatch;
import com.itic.mall.system.weixinbatch.persistence.model.WeixinBatchExample;
import com.itic.mall.system.weixinbatch.persistence.model.WeixinBatchExample.Criteria;
import com.itic.mall.system.weixinbatch.service.WeixinBatchService;
import com.itic.mall.mobile.jd.MallJdUtils;
import com.itic.mall.system.productjd.persistence.model.ProductJd;
import com.itic.mall.system.productjd.persistence.model.ProductJdExample;
import com.itic.mall.system.productjd.service.ProductJdService;


@Controller
@RequestMapping(value="/system/weixinbatch")
public class WeixinBatchController
     extends BaseController {
	@Autowired
    private WeixinBatchService weixinBatchService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductJdService productJdService;
    @Autowired
	protected OutCommonService outCommonService;
       
    
    //////////////////////////////////////////////////////常量区////////////////////////////////////////////////////////////////weixinbatch:check
    private static final String MODEL_NAME_CHINA = "微信群发";//中文名
    private static final String MODEL_NAME＿ENGLISH = "weixinbatch";//英文名
    private static final String PAGE_COMMON_PATH = "/mall/system/weixinbatch/weixinbatch";//通用路径
    private static final String COMMON_URL = "/system/weixinbatch/";//通用路径


    //////////////////////////////////////////////////////页面跳转区////////////////////////////////////////////////////////////
   
    /*
     * 主页面
     */
    @RequestMapping(value="/init")
    public String init(Model model){
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Main";
    }
    
    /*
     * 添加页面
     */
    @RequestMapping(value="/initAdd")
    public String initAdd(String id,Model model){
    	if( StringHelper.isNotBlank(id) ){
    		model.addAttribute("parentId", id);
    	}
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Add";
    }
    
    /*
     * 编辑页面
     */
    @RequestMapping(value="/initEdit")
    public String initEdit(String id , Model model){
    	if( StringHelper.isNotBlank(id) ) {
    		WeixinBatch temp = weixinBatchService.get(id);
    		model.addAttribute("editData",iticJsonMapper.toJson(temp));
    		model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
    	}else {
            throw new ParameterErrorException();
        }
    	return PAGE_COMMON_PATH+"Edit";
    }
    
    /*
     * 查看页面
     */
    @RequestMapping(value="/initView")
    public String initView(String id , Model model){
    	if( StringHelper.isNotBlank(id) ) {
    		
    		WeixinBatch temp  = weixinBatchService.get(id);
    		
    		List<Product> list = new ArrayList<Product>();
    		String productIds = temp.getProductIds();
    		String[] split = productIds.split(",");
    		for( int i=0;i<split.length; i++ ){
    			Product product = productService.get(split[i]);
    			list.add(product);
    		}
    		model.addAttribute("viewEdit",iticJsonMapper.toJson(temp));
    		model.addAttribute("products",iticJsonMapper.toJson(list));
    		
    		model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
    	}else {
            throw new ParameterErrorException();
        }
    	
    	return PAGE_COMMON_PATH+"View";
    }
    
    /*
     * 导入页面
     */
    @RequestMapping(value="/initImp")
    public String initImp(Model model){
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Imp";
    }
    
    
    //////////////////////////////////////////////////////业务代码区////////////////////////////////////////////////////////////
    
    /**
     * 添加模板管理数据
     * @param android
     * @return
     */
    @RequestMapping(value="/add")
    @ResponseBody
    public Map<String,String> add(WeixinBatch temp){
    	
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         String productIds = temp.getProductIds();
         String productJdIds = temp.getProductJdIds();
         
         String content = "";
         
         if( StringHelper.isNotBlank(productJdIds) ){
        	 String[] split1 = productJdIds.split(",");
             content += ",共"+split1.length+"个京东精品";
         }
         
         if( StringHelper.isNotBlank(productIds) ){
        	 String[] split = productIds.split(",");
             content += ",共"+split.length+"个友惠精品";
         }
         
         temp.setContent(content.substring(1, content.length()));
         
         result = weixinBatchService.add(temp);
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    
    /**
     * <p>Title:queryCondition </p>
     * <p>Description:封装查询条件 </p>
     * @param jzdw
     * @param jzdwExample
     * @return
     */
    private WeixinBatchExample queryCondition(HttpServletRequest request,WeixinBatch temp) {
    	
    	// 参数处理
        WeixinBatchExample example = new WeixinBatchExample();
        // 按创建时间倒序
        example.setOrderByClause("create_time desc");
        // 按排列号顺序
        example.setOrderByClause("reorder asc");
        
        Criteria criteria = example.createCriteria().andIsEffectiveEqualTo( DBConst.TRUE );
      
        // 查询条件
        if ( null != temp ) {
    	    //模糊查询
            if ( StringHelper.isNotBlank( temp.getName() ) ) {
                criteria.andNameLike("%" + temp.getName() + "%");
            }
            
            if( StringHelper.isNotBlank( temp.getType()) ){
            	criteria.andTypeEqualTo(temp.getType());
            }
        }
        return example;
    }
    
    /**
     * 
     * @param goldType
     * @param request
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list(WeixinBatch temp, HttpServletRequest request){
        // 声明返回对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        
        WeixinBatchExample example = this.queryCondition(request,temp);
        // 封装分页参数
        example = this.handlePageQuery(request, example);
        
        
        // 获取信息总条数
        int total = weixinBatchService.count(example);
        
        // 获取数据
        List<WeixinBatch> list = weixinBatchService.list(example);
        
        
        // 数据返回处理
        resultMap.put(IticConst.TOTAL_RECORDS, total);
        resultMap.put(IticConst.DISPLAY_RECORDS, total);
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        resultMap.put(IticConst.DATA, list);
        return resultMap;

    }
    
    
    /**
     * 编辑保存
     * @param WeixinBatch
     * @return
     */
    @RequestMapping(value="/edit")
    @ResponseBody
    public Map<String,String> edit(String delFileIds , WeixinBatch temp){
    
    	
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         
         String productIds = temp.getProductIds();
         String productJdIds = temp.getProductJdIds();
         
         String content = "";
         if( StringHelper.isNotBlank(productJdIds) ){
        	 String[] split1 = productJdIds.split(",");
             content += ",共"+split1.length+"个京东精品";
         }
         
         if( StringHelper.isNotBlank(productIds) ){
        	 String[] split = productIds.split(",");
             content += ",共"+split.length+"个友惠精品";
         }
         temp.setContent(content.substring(1, content.length()));
         
         result = weixinBatchService.edit(temp);
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    

    /**
     * 删除
     * 
     */
    @RequestMapping(value = "/del")
    @ResponseBody
    public Map<String, String> del(String id) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();

        //批量删除
        /*if (StringHelper.isNotBlank(ids)) {
        	
            List<String> idList = Arrays.asList(ids.split(","));
            
            WeixinBatchExample example = new WeixinBatchExample();
            example.createCriteria().andIdIn(idList);
          
            WeixinBatch temp = new WeixinBatch();
            result = weixinBatchService.deleteByExample(temp, example);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }*/

        //删除一个
        if( StringHelper.isNotBlank(id) ){
            WeixinBatch WeixinBatch = new WeixinBatch();
            WeixinBatch.setId(id);
            result = weixinBatchService.delete(WeixinBatch);
        }
        
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }
    
    
    /**
     * 删除
     * 
     */
    @RequestMapping(value = "/products")
    @ResponseBody
    public List<Product> products() {
        ProductExample example = new ProductExample();
        example.setOrderByClause("CREATE_TIME DESC");
        com.itic.mall.system.product.persistence.model.ProductExample.Criteria criteria = example.createCriteria();
        criteria.andIsEffectiveEqualTo(DBConst.TRUE);
        return productService.list(example);
    }
    
    
    /**
     * 删除
     * 
     */
    @RequestMapping(value = "/listProduct")
    @ResponseBody
    public Map<String, Object> listProduct( HttpServletRequest request, String name ) {
    	  // 声明返回对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        ProductExample example = new ProductExample();
        example.setOrderByClause("CREATE_TIME DESC");
        com.itic.mall.system.product.persistence.model.ProductExample.Criteria criteria = example.createCriteria();
        criteria.andIsEffectiveEqualTo(DBConst.TRUE);
        if( StringHelper.isNotBlank(name) ){
        	criteria.andNameLike("%"+name+"%");
        }
        int count = productService.count(example);
        handlePageQuery(request, example);
        List<Product> list = productService.list(example);
        // 数据返回处理
        resultMap.put(IticConst.TOTAL_RECORDS, count);
        resultMap.put(IticConst.DISPLAY_RECORDS, count);
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        resultMap.put(IticConst.DATA, list);
        return resultMap;
    }
    
    /**
     * 删除
     * 
     */
    @RequestMapping(value = "/listProductJd")
    @ResponseBody
    public Map<String, Object> listProductJd( HttpServletRequest request, String name ) {
    	  // 声明返回对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        ProductJdExample example = new ProductJdExample();
        example.setOrderByClause("REORDER DESC");
        com.itic.mall.system.productjd.persistence.model.ProductJdExample.Criteria criteria = example.createCriteria();
        criteria.andIsEffectiveEqualTo(DBConst.TRUE);
        criteria.andConUrlBIsNotNull();
        if( StringHelper.isNotBlank(name) ){
        	criteria.andGoodsNameLike("%"+name+"%");
        }
       
        handlePageQuery(request, example);
        int count = productJdService.count(example);
        List<ProductJd> list = productJdService.list(example);
        // 数据返回处理
        resultMap.put(IticConst.TOTAL_RECORDS, count);
        resultMap.put(IticConst.DISPLAY_RECORDS, count);
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        resultMap.put(IticConst.DATA, list);
        return resultMap;
    }
    
    /**
     * 删除
     * 
     */
    @RequestMapping(value = "/jds")
    @ResponseBody
    public List<ProductJd> jds() {
        ProductJdExample example = new ProductJdExample();
        example.setOrderByClause("CREATE_TIME DESC");
        com.itic.mall.system.productjd.persistence.model.ProductJdExample.Criteria criteria = example.createCriteria();
        criteria.andIsEffectiveEqualTo(DBConst.TRUE);
        return productJdService.list(example);
    }
    
    /**
     * 删除
     * 
     */
    @RequestMapping(value = "/check")
    @ResponseBody
    public Map<String, String> check(String id) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();

        //删除一个
        if( StringHelper.isNotBlank(id) ){
           ProductJd productJd = productJdService.get(id);
           String convert = MallJdUtils.convert("0", productJd.getSku(), productJd.getConUrlB());
           if( null != convert ){
        	   result = "success";
           }else{
        	   productJdService.delete(productJd);
        	   result = "fail";
           }
        }
        
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

}